﻿import cgi
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from Entities import *
#---------------------------
# Entities DoiTuongNguoiDung
#---------------------------
def GetDoiTuongID(keyNguoiDung = None,DoiTuongID=0):
    dtNd_list = []
    results = DoiTuong_NguoiDung.all()
    if keyNguoiDung !=None:
        try:
            nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
        except:
            return "Invalid Key"	
    results.filter('NguoiDung',nguoidung)
    if DoiTuongID > 0:
            doituong = DoiTuong.get_by_id(DoiTuongID)
            results = results.filter("DoiTuongID", doituong)
    for dtNd in results:		
        dtNd_list.append(dtNd.DoiTuongID.key()) 
    return dtNd_list
    
def Delete(keyNguoiDung, DoiTuongID):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"	
    results = DoiTuong_NguoiDung.all().filter("NguoiDung",nguoidung)
    if int(DoiTuongID) > 0 :
        doituong = DoiTuong.get_by_id(int(DoiTuongID))
        results = results.filter("DoiTuongID", doituong)
    for dtNd in results :
        DoiTuong_NguoiDung.delete(dtNd)  
    return "Complete"

def Add(keyNguoiDung,DoiTuongID):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"
    doituong = DoiTuong.get_by_id(DoiTuongID)
    if doituong != None:
        dtNd_check = DoiTuong_NguoiDung.all().filter("DoiTuongID", doituong).filter("NguoiDung", nguoidung)
        if dtNd_check.count() == 0:                
            dtNd = DoiTuong_NguoiDung(DoiTuongID = doituong,NguoiDung = nguoidung)
            dtNd.put()         
            return "Complete"
        else:
            return "Duplicate"
    else:
        return "Error"

def Update(keyNguoiDung,NhaTuyenDungID):
    nganhnghe_update = NganhNghe.get_by_id(NganhNgheID)
    linhvuc = LinhVuc.get_by_id(LinhVucID)
    nganhnghe = db.GqlQuery("SELECT * FROM NganhNghe WHERE TenNganhNghe = :1 AND LinhVucID = :2 AND NguoiDung = :3",
                              TenNganhNghe, linhvuc, nguoidung)
    if linhvuc.count > 0 and nganhnghe_update.count > 0 : 
        if nganhnghe.count() == 0:
            nganhnghe_update.TenNganhNghe = TenNganhNghe
            nganhnghe_update.LinhVucID = linhvuc
            nganhnghe_update.put()
            return "Complete"
        else:
            return "Duplicate"
    else:
        return "Error"